package com.xgkj.diyiketang.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.xgkj.diyiketang.ProtocolConst;
import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.data.EatShowUserInfo;
import com.xgkj.diyiketang.data.OrderInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.http.engine.TaskEventListener;
import com.xgkj.diyiketang.task.BuyGoldCoinTask;
import com.xgkj.diyiketang.task.MyYueBianHuaTask;
import com.xgkj.diyiketang.util.DialogUtil;
import com.xgkj.diyiketang.util.ToastUtil;
import com.xgkj.diyiketang.util.WeiXinPay;
import com.xgkj.diyiketang.weidget.CompoundView;
import com.xgkj.diyiketang.weidget.NestCompoundGroup;
import com.xgkj.eatshow.wxapi.WXPayEntryActivity;

import java.util.ArrayList;
import java.util.List;

public class MyFlowerActivity extends BaseActivity implements View.OnClickListener, NestCompoundGroup.OnCheckedChangeListener {

    private final String TAG = getClass().getSimpleName();
    private Context mContext;

    private RelativeLayout titleLayout;
    private TextView back;
    private TextView flourYijihuo;
    private TextView flourDaijihuo;
    private NestCompoundGroup rechargeGoldcoinGroup;
    private CompoundView recharge1;
    private RadioButton rechargeBtn1;
    private RadioButton giveBtn1;
    private CompoundView recharge2;
    private RadioButton rechargeBtn2;
    private RadioButton giveBtn2;
    private CompoundView recharge3;
    private RadioButton rechargeBtn3;
    private RadioButton giveBtn3;
    private CompoundView recharge4;
    private RadioButton rechargeBtn4;
    private RadioButton giveBtn4;
    private CompoundView recharge5;
    private RadioButton rechargeBtn5;
    private RadioButton giveBtn5;
    private CompoundView recharge6;
    private RadioButton rechargeBtn6;
    private RadioButton giveBtn6;
    private RelativeLayout weixinpayLayout;
    private ImageView weixinCheck;
    private RelativeLayout yuepayLayout;
    private ImageView yueCheck;
    private int currentPage = 1;
    private int size = 10;
    private int mYueChangeTaskId = -1;
    private int mCheckedId;
    private String rechargeMoney;
    private ProgressDialog mProgressDialog;
    private IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
    private int getOrderTaskId = -1;
    private String rechargeType;
    private BroadcastReceiver mWeiXinReceive;
    private String orderNo;
    private String orderBody;
    private Button coinTixianBtn;
    private int shenfen;
    private String realLiveCoin;
    private TextView mShouyiBtn;
    //转赠花朵
    private Button mTvTransFlower;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_flower);
        mContext = this;
        msgApi.registerApp(ProtocolConst.APP_ID);
        initView();

    }

    private void initView() {
        EatShowUserInfo mUserInfo = getEatShowApp().getmUserInfo();
        if (mUserInfo != null) {
            shenfen = mUserInfo.getUserType();
        }
        titleLayout = (RelativeLayout) findViewById(R.id.title_layout);
        mShouyiBtn = (TextView) findViewById(R.id.shouyijilu);
        back = (TextView) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        flourYijihuo = (TextView) findViewById(R.id.flour_yijihuo);
        flourDaijihuo = (TextView) findViewById(R.id.flour_daijihuo);
        rechargeGoldcoinGroup = (NestCompoundGroup) findViewById(R.id.recharge_goldcoin_group);
        rechargeGoldcoinGroup.setOnCheckedChangeListener(this);
        recharge1 = (CompoundView) findViewById(R.id.recharge1);
        rechargeBtn1 = (RadioButton) findViewById(R.id.recharge_btn1);
        giveBtn1 = (RadioButton) findViewById(R.id.give_btn1);
        recharge2 = (CompoundView) findViewById(R.id.recharge2);
        rechargeBtn2 = (RadioButton) findViewById(R.id.recharge_btn2);
        giveBtn2 = (RadioButton) findViewById(R.id.give_btn2);
        recharge3 = (CompoundView) findViewById(R.id.recharge3);
        rechargeBtn3 = (RadioButton) findViewById(R.id.recharge_btn3);
        giveBtn3 = (RadioButton) findViewById(R.id.give_btn3);
        recharge4 = (CompoundView) findViewById(R.id.recharge4);
        rechargeBtn4 = (RadioButton) findViewById(R.id.recharge_btn4);
        giveBtn4 = (RadioButton) findViewById(R.id.give_btn4);
        recharge5 = (CompoundView) findViewById(R.id.recharge5);
        rechargeBtn5 = (RadioButton) findViewById(R.id.recharge_btn5);
        giveBtn5 = (RadioButton) findViewById(R.id.give_btn5);
        recharge6 = (CompoundView) findViewById(R.id.recharge6);
        rechargeBtn6 = (RadioButton) findViewById(R.id.recharge_btn6);
        giveBtn6 = (RadioButton) findViewById(R.id.give_btn6);
        weixinpayLayout = (RelativeLayout) findViewById(R.id.weixinpay_layout);
        weixinpayLayout.setOnClickListener(this);
        weixinCheck = (ImageView) findViewById(R.id.weixin_check);
        yuepayLayout = (RelativeLayout) findViewById(R.id.yuepay_layout);
        yuepayLayout.setOnClickListener(this);
        yueCheck = (ImageView) findViewById(R.id.yue_check);
        findViewById(R.id.zhifu_btn).setOnClickListener(this);
        recharge1.setChecked(true);
        rechargeType = "1";
        coinTixianBtn = (Button) findViewById(R.id.coin_withdraw);
        coinTixianBtn.setOnClickListener(this);
        mTvTransFlower = (Button) findViewById(R.id.trans_text_flower);
        mTvTransFlower.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext,ChooseTransFriendFlower.class);
                startActivity(intent);
            }
        });
//        if (shenfen == 1) {
//        关闭小红花提现功能
//        coinTixianBtn.setVisibility(View.VISIBLE);
        mShouyiBtn.setVisibility(View.VISIBLE);
        mShouyiBtn.setOnClickListener(this);
//        } else {
//            coinTixianBtn.setVisibility(View.GONE);
//            mShouyiBtn.setVisibility(View.GONE);
//        }

        getYueChangeList();
    }

    private void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = DialogUtil.showProgressDialog(mContext, getString(R.string.get_ordering), new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    getEatShowApp().getTaskManager().cancelTask(getOrderTaskId);
                }
            });
        }
    }

    private void dismissDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }

    private void getOrder() {
        showProgressDialog();
        BuyGoldCoinTask task = new BuyGoldCoinTask(rechargeType, rechargeMoney);
        task.addListener(changelistener);
        getOrderTaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    private void doWeixinPay() {
        if (!msgApi.isWXAppSupportAPI() || !msgApi.isWXAppInstalled()) {
            ToastUtil.showMessage(mContext, R.string.need_weixin_app);
            return;
        }

        if (mWeiXinReceive == null) {
            mWeiXinReceive = new WeixinReceive();
            IntentFilter filter = new IntentFilter();
            filter.addAction(WXPayEntryActivity.WEIXIN_PAY_SUCCESS_ACTION);
            registerReceiver(mWeiXinReceive, filter);
        }
        new WeiXinPay(msgApi, MyFlowerActivity.this, orderNo, orderBody, rechargeMoney);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.zhifu_btn:
                getOrder();
                break;
            case R.id.weixinpay_layout:
                rechargeType = "1";
                weixinCheck.setVisibility(View.VISIBLE);
                yueCheck.setVisibility(View.GONE);
                break;
            case R.id.yuepay_layout:
                rechargeType = "0";
                weixinCheck.setVisibility(View.GONE);
                yueCheck.setVisibility(View.VISIBLE);
                break;
            case R.id.coin_withdraw:
                Intent intent = new Intent(mContext, TiXianActivity.class);
//                intent.putExtra("coinBalance",coinBalance);
                intent.putExtra("realLiveCoin", realLiveCoin);
                intent.putExtra("from", 1);
                startActivity(intent);
                break;
            case R.id.shouyijilu:
                Intent sintent = new Intent(mContext, MyShouYiActivity.class);
                startActivity(sintent);
                finish();
                break;

        }
    }


    private void getYueChangeList() {
        if (mYueChangeTaskId != -1) {
            return;
        }
        if (currentPage == 0) {
//            mListView.setNoNextPage();
            return;
        }

        MyYueBianHuaTask stask = new MyYueBianHuaTask(size, currentPage);
        stask.addListener(changelistener);
        mYueChangeTaskId = getEatShowApp().getTaskManager().addTask(stask);

    }

    private TaskEventListener changelistener = new ShowToastTaskEventListener(this) {
        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            if (taskId == mYueChangeTaskId) {
                mYueChangeTaskId = -1;
                List<OrderInfo> mfoodlist = new ArrayList<OrderInfo>();
                if (data != null) {
                    JSONObject jsonString = (JSONObject) data;
                    String yue = jsonString.getString("nowBalance");
                    realLiveCoin = jsonString.getString("unlockFlowerCount");
                    String locked = jsonString.getString("lockFlowerCount");
                    String unlocked = jsonString.getString("unlockFlowerCount");
                    flourYijihuo.setText(unlocked + "朵");
                    flourDaijihuo.setText(locked + "朵");

                }
            } else if (taskId == getOrderTaskId) {
                dismissDialog();
                if (rechargeType.equals("0")) {
                    ToastUtil.showMessage(mContext, R.string.recharge_flower_success);
                    getYueChangeList();
                } else if (rechargeType.equals("1")) {
                    orderNo = (String) data;
                    doWeixinPay();
                }
            }
        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
            if (taskId == mYueChangeTaskId) {
                mYueChangeTaskId = -1;
            } else if (taskId == getOrderTaskId) {
                getOrderTaskId = -1;
                dismissDialog();
            }
        }


        @Override
        public void handleTaskMessage(int taskId, Object data) {
            super.handleTaskMessage(taskId, data);
        }
    };

    @Override
    public void onCheckedChanged(NestCompoundGroup group, int checkedId) {
        if (mCheckedId == checkedId) return;
        mCheckedId = checkedId;
        switch (checkedId) {
            case R.id.recharge1:
                rechargeMoney = "6";
                orderBody = "充值60朵花";
                break;
            case R.id.recharge2:
                rechargeMoney = "30";
                orderBody = "充值300朵花";
                break;
            case R.id.recharge3:
                rechargeMoney = "98";
                orderBody = "充值980朵花";
                break;
            case R.id.recharge4:
                rechargeMoney = "298";
                orderBody = "充值2980朵花";
                break;
            case R.id.recharge5:
                rechargeMoney = "588";
                orderBody = "充值5880朵花";
                break;
            case R.id.recharge6:
                rechargeMoney = "1598";
                orderBody = "充值15980朵花";
                break;
        }
    }

    class WeixinReceive extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            boolean isSuccess = intent.getBooleanExtra(ProtocolConst.WEIXINPAY_SUCCESS, false);
            if (isSuccess) {
                ToastUtil.showMessage(mContext, R.string.recharge_flower_success);
                getYueChangeList();
            }
            if (mWeiXinReceive != null) {
                unregisterReceiver(mWeiXinReceive);
                mWeiXinReceive = null;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mWeiXinReceive != null) {
            unregisterReceiver(mWeiXinReceive);
            mWeiXinReceive = null;
        }
    }
}
